package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageDTO;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.vo.CategoryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import com.sky.service.CategoryService;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService{

    private final CategoryMapper categoryMapper;

    @Autowired
    public CategoryServiceImpl(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    /**
     * 分页查询获取所有的分类
     */
    @Override
    public PageResult list(CategoryPageDTO categoryPageDTO) {
        PageHelper.startPage(categoryPageDTO.getPage(), categoryPageDTO.getPageSize());

        Page<CategoryVO> page = categoryMapper.list(categoryPageDTO);
        long total = page.getTotal();
        List<CategoryVO> records = page.getResult();
        return new PageResult(total, records);

    }

    /**
     * 新增分类
     */
    @Override
    @PreAuthorize("@rootPermission.hasRoot(1L)")
    public void create(CategoryDTO categoryDTO) {
        categoryMapper.create(categoryDTO);
    }

    /**
     * 删除分类
     */
    @Override
    @PreAuthorize("@rootPermission.hasRoot(1L)")
    public void delete(Long id) {
         categoryMapper.delete(id);
    }

    /**
     * 根据id查询分类
     * @param id
     * @return
     */
    @Override
    public CategoryVO getById(Long id) {
        return categoryMapper.getById(id);
    }

    /**
     * 修改分类
     * @param categoryDTO
     */
    @Override
    @PreAuthorize("@rootPermission.hasRoot(1L)")
    public void update(CategoryDTO categoryDTO) {
        categoryMapper.update(categoryDTO);
    }

    /**
     * 统计分类数量
     * @return
     */
    @Override
    public Long countCategory() {
        Long count = categoryMapper.countCategory();
        if (count == null) {
            return 0L;
        }
        return count;
    }

    @Override
    public List<String> findAllCategoryName() {
        return categoryMapper.findAllCategoryName();
    }
}
